package com.tianyalei.wolf.sample.activity.wxcircle.listener;

import android.annotation.SuppressLint;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

import com.tianyalei.wolf.mddesignlib.view.autorecyclerview.callback.LoadMoreListener;

/**
 * @author yiw
 * @ClassName: SwpipeListViewOnScrollListener
 * @Description: 解决SwipeRefreshLayout和listview的滑动冲突事件
 * @date 2015-12-28 下午4:17:48
 */
public class SwpipeListViewOnScrollListener implements OnScrollListener {

    private SwipeRefreshLayout mSwipeView;
    private OnScrollListener mOnScrollListener;
    private LoadMoreListener loadMoreListener;
    private boolean isLoadingMore;

    public SwpipeListViewOnScrollListener(SwipeRefreshLayout swipeView) {
        mSwipeView = swipeView;
        isLoadingMore = false;
    }

    public void setLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }

    public SwpipeListViewOnScrollListener(SwipeRefreshLayout swipeView,
                                          OnScrollListener onScrollListener) {
        mSwipeView = swipeView;
        mOnScrollListener = onScrollListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @SuppressLint("NewApi")
    @Override
    public void onScroll(AbsListView absListView, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        View firstView = absListView.getChildAt(0);

        // 当firstVisibleItem是第0位。如果firstView==null说明列表为空，需要刷新;或者top==0说明已经到达列表顶部, 也需要刷新
        if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0)) {
            mSwipeView.setEnabled(true);
        } else {
            mSwipeView.setEnabled(false);
        }
        if (null != mOnScrollListener) {
            mOnScrollListener.onScroll(absListView, firstVisibleItem,
                    visibleItemCount, totalItemCount);
        }

        //有回调接口，并且不是加载状态，并且剩下2个item，并且向下滑动，则自动加载
        if (loadMoreListener != null && !isLoadingMore && (firstVisibleItem + visibleItemCount) >= totalItemCount - 2) {
            loadMoreListener.loadMore();
            isLoadingMore = true;
        }
    }

    public void loadFinish(Object obj) {
        isLoadingMore = false;
    }
}